package logic

import (
	"context"
	"encoding/json"
	"fmt"

	"book/common/errorx"
	"book/service/search/cmd/api/internal/svc"
	"book/service/search/cmd/api/internal/types"
	"book/service/search/model"
	"book/service/user/cmd/rpc/userclient"

	"github.com/tal-tech/go-zero/core/logx"
)

type SearchLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSearchLogic(ctx context.Context, svcCtx *svc.ServiceContext) SearchLogic {
	return SearchLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SearchLogic) Search(req types.SearchReq) (resp interface{}, err error) {

	userIdNumber := json.Number(fmt.Sprintf("%v", l.ctx.Value("userId")))
	logx.Infof("userId: %s", userIdNumber)
	userId, err := userIdNumber.Int64()
	if err != nil {
		return nil, err
	}

	logx.Infof("userId: %v", userId)

	// 使用user rpc
	userInfo, err := l.svcCtx.UserRpc.GetUser(l.ctx, &userclient.IdReq{
		Id: userId,
	})
	if err != nil {
		return nil, err
	}

	logx.Infof("userName:%v", userInfo.Name)

	nameStr := fmt.Sprintf("%v", req.Name)

	searchInfo, err := l.svcCtx.SearchModel.FindOneByUserIdAndName(userId, nameStr)

	var count int64 = 1
	if err != nil {
		if searchInfo.Id == 0 {
			l.svcCtx.SearchModel.Insert(&model.Search{
				UserId: userId,
				Name:   nameStr,
				Count:  count,
			})
		} else {
			return nil, err
		}
	} else {
		logx.Infof("Id： %v", searchInfo.Id)

		count = searchInfo.Count + count
		l.svcCtx.SearchModel.Update(&model.Search{
			Id:     searchInfo.Id,
			UserId: userId,
			Name:   nameStr,
			Count:  count,
		})
	}

	return errorx.NewCodeSuccess(&types.SearchReply{
		Name:  nameStr,
		Count: count,
	}, "success"), nil
}
